﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.SpatialAnalystTools;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Geoprocessor;
//using ESRI.ArcGIS.SpatialAnalyst;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;

namespace School
{
    public partial class Weight : Form
    {
        private IMapControl3 mapControl;
        private CheckedListBox checkedListBoxLayer;
        private ProgressBar progressBar1;
        private Button btnRun;

        private Dictionary<string, double> layerWeights = new Dictionary<string, double>();

        public Weight(IMapControl3 mapControl)
        {
            InitializeComponent();
            this.mapControl = mapControl;
            InitializeUI();
            InitializeEvents();
            RefreshLayerList();
        }

        private void InitializeUI()
        {
            this.Text = "栅格加权叠加";
            this.Size = new Size(600, 450);
            this.StartPosition = FormStartPosition.CenterScreen;

            checkedListBoxLayer = new CheckedListBox { Location = new Point(20, 40), Size = new Size(540, 250) };
            btnRun = new Button { Location = new Point(250, 300), Size = new Size(100, 30), Text = "运行加权" };
            progressBar1 = new ProgressBar { Location = new Point(80, 340), Size = new Size(480, 23) };

            this.Controls.Add(new Label { Text = "选择参与加权的栅格图层:", Location = new Point(20, 20) });
            this.Controls.Add(checkedListBoxLayer);
            this.Controls.Add(btnRun);
            this.Controls.Add(new Label { Text = "状态:", Location = new Point(20, 340) });
            this.Controls.Add(progressBar1);
        }

        private void InitializeEvents()
        {
            btnRun.Click += BtnRun_Click;
        }

        private void RefreshLayerList()
        {
            checkedListBoxLayer.Items.Clear();
            for (int i = 0; i < mapControl.Map.LayerCount; i++)
            {
                ILayer lyr = mapControl.Map.get_Layer(i);
                if (lyr is IRasterLayer)
                    checkedListBoxLayer.Items.Add(lyr.Name, true);
            }
        }

        private void BtnRun_Click(object sender, EventArgs e)
        {
            var selected = checkedListBoxLayer.CheckedItems.Cast<string>().ToList();
            if (selected.Count == 0)
            {
                MessageBox.Show("请至少选择一个栅格图层进行加权叠加。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            layerWeights.Clear();
            foreach (var layerName in selected)
            {
                using (var inputForm = new InputForm($"请输入图层"+ layerName +"的权重值", "1"))
                {
                    if (inputForm.ShowDialog() == DialogResult.OK)
                    {
                        if (double.TryParse(inputForm.InputValue, out double weight))
                        {
                            layerWeights[layerName] = weight;
                        }
                        else
                        {
                            MessageBox.Show("请输入有效的权重值！", "错误");
                            return;
                        }
                    }
                    else
                    {
                        return; // 用户取消了输入
                    }
                }
            }

            var layersToProcess = selected.Where(layerName => layerWeights.ContainsKey(layerName)).ToList();

            if (layersToProcess.Count == 0)
            {
                MessageBox.Show("没有可用于加权叠加的有效图层（可能您取消了权重输入或输入了无效值）。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            PerformWeightedOverlay(layersToProcess);
        }

        public class InputForm : Form
        {
            public string InputValue { get; private set; }
            private TextBox textBox;

            public InputForm(string prompt, string defaultValue)
            {
                InitializeComponent(prompt, defaultValue);
            }

            private void InitializeComponent(string prompt, string defaultValue)
            {
                this.Text = "输入权重";
                this.Size = new Size(300, 150);
                this.StartPosition = FormStartPosition.CenterParent;

                Label label = new Label { Text = prompt, Location = new Point(10, 20), Width = 260 };
                textBox = new TextBox { Text = defaultValue, Location = new Point(10, 50), Width = 260 };
                Button btnOk = new Button { Text = "确定", DialogResult = DialogResult.OK, Location = new Point(100, 80) };

                btnOk.Click += (s, e) => { InputValue = textBox.Text; this.Close(); };

                this.Controls.Add(label);
                this.Controls.Add(textBox);
                this.Controls.Add(btnOk);
            }
        }

        private void PerformWeightedOverlay(List<string> layerNames)
        {
            using (var sfd = new SaveFileDialog())
            {
                sfd.Filter = "TIFF 栅格|*.tif";
                sfd.Title = "保存加权叠加结果";
                sfd.FileName = "WeightedOverlayResult.tif";
                if (sfd.ShowDialog() != DialogResult.OK) return;

                string outputPath = sfd.FileName;

                progressBar1.Value = 0;
                progressBar1.Maximum = layerNames.Count;

                try
                {
                    List<IRasterLayer> rasterLayers = new List<IRasterLayer>();

                    foreach (var layerName in layerNames)
                    {
                        var lyr = GetLayerByName(layerName) as IRasterLayer;
                        if (lyr != null && lyr.Raster != null)
                        {
                            rasterLayers.Add(lyr);
                        }
                        else
                        {
                            MessageBox.Show($"图层" + layerName + "不是有效的栅格图层或其数据源不可用，将被跳过。",
                                          "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        progressBar1.Value++;
                    }

                    if (rasterLayers.Count == 0)
                    {
                        MessageBox.Show("没有找到任何有效的栅格图层进行加权叠加。", "提示",
                                      MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 关键修改：获取栅格数据集的完整路径
                    string expression = string.Join(" + ", rasterLayers.Select(lyr =>
                    {
                        // 获取栅格数据集的工作空间路径
                        IRasterDataset rasterDataset = (lyr.Raster as IRaster2)?.RasterDataset;
                        IDataset dataset = rasterDataset as IDataset;
                        string fullPath = dataset?.Workspace.PathName + "\\" + dataset?.Name;

                        double weight = layerWeights[lyr.Name];
                        return $"(\"{fullPath}\" * {weight})";
                    }));

                    IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                    geoProcessor.OverwriteOutput = true;

                    // 设置工作空间（重要！）
                    geoProcessor.SetEnvironmentValue("workspace", System.IO.Path.GetDirectoryName(outputPath));

                    IVariantArray parameters = new VarArrayClass();
                    parameters.Add(expression);
                    parameters.Add(outputPath);

                    // 添加调试信息
                    Console.WriteLine("执行的表达式: " + expression);

                    // 执行工具
                    geoProcessor.Execute("RasterCalculator_sa", parameters, null);

                    // 添加结果图层到地图中
                    AddResultLayerToMap(outputPath);

                    MessageBox.Show("加权叠加完成！结果已保存到:\n" + outputPath + "\n并已添加到地图中。",
                                  "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加权叠加出错: {ex.Message}\n详细信息:\n{ex.StackTrace}",
                                  "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    progressBar1.Value = 0;
                }
            }
        }

        // 将结果栅格添加到地图中
        private void AddResultLayerToMap(string rasterPath)
        {
            try
            {
                // 创建栅格图层
                IRasterLayer rasterLayer = new RasterLayerClass();

                // 创建栅格数据集
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(
                    Path.GetDirectoryName(rasterPath), 0);

                IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(Path.GetFileName(rasterPath));

                // 设置栅格图层的名称和数据源
                rasterLayer.CreateFromDataset(rasterDataset);
                rasterLayer.Name = "加权叠加结果_" + DateTime.Now.ToString("yyyyMMdd_HHmmss");

                // 添加到地图的最上层
                mapControl.Map.AddLayer(rasterLayer);

                // 刷新地图显示
                mapControl.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加结果图层到地图时出错: {ex.Message}", "警告",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private ILayer GetLayerByName(string name)
        {
            for (int i = 0; i < mapControl.Map.LayerCount; i++)
            {
                var lyr = mapControl.Map.get_Layer(i);
                if (lyr.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                    return lyr;
            }
            return null;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}